package com.baselibs.utils;

import android.graphics.Bitmap;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 日期：2017.01.12
 * <p>
 * 作者：xudiwei
 * <p>
 * 描述：文件工具类
 */
public class FileUtils {
    private static final String TAG = "FileUtils";

    /**
     * 根据路径创建一个在sd卡目录下的一个文件夹
     *
     * @param dirPath 文件夹名
     * @return 返回创建成功的File对象或是null.
     */
    public static File createDirToSDCard(String dirPath) {
        if (TextUtils.isEmpty(dirPath)) {
            throw new IllegalArgumentException("dir path can not empty");
        }

        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File dir; /*= Environment.getExternalStoragePublicDirectory(dirPath);*/
            dir = new File(Environment.getExternalStorageDirectory(), dirPath);
            boolean mkdirs = dir.mkdirs() || dir.isDirectory();
            return dir;
        }
        return null;
    }

    /**
     * 创建一个文件，如果已存在则册除后再创建
     *
     * @param dir
     * @param filename
     * @return
     */
    public static File createFile(File dir, String filename) {
        File file = new File(dir, filename);
        try {
            if (file.exists()) {
                boolean deleteResult = file.delete();
            }
            boolean createResult = file.createNewFile();
            Log.d(TAG, "createFile: " + createResult);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 册除一个已存在的文件
     *
     * @param dir
     * @param name
     * @return
     */
    public static boolean deleteFile(String dir, String name) {
        File file = new File(createDirToSDCard(dir), name);
        if (file.exists() && file.isFile()) {
            boolean deleteResult = file.delete();
            Log.d(TAG, "deleteFile:  " + deleteResult);
            return deleteResult;
        }
        return false;
    }

    /**
     * 删除文件夹里面的所以文件
     */
    public static void deleteDir(File dir) {
        if (dir.exists()) {
            File[] files = dir.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile()) {
                    files[i].delete();
                } else {
                    deleteDir(files[i]);
                }
            }
        }
    }


    /**
     * 统计文件夹文件的大小
     */
    public static long getSize(File file) {
        // 判断文件是否存在
        if (file.exists()) {
            // 如果是目录则递归计算其内容的总大小，如果是文件则直接返回其大小
            if (!file.isFile()) {
                // 获取文件大小
                File[] fl = file.listFiles();
                long ss = 0;
                for (File f : fl)
                    ss += getSize(f);
                return ss;
            } else {
                long ss = (long) file.length();
                return ss; // 单位制bytes
            }
        } else {
            // System.out.println("文件或者文件夹不存在，请检查路径是否正确！");
            return 0;
        }
    }

    /**
     * 编码Base64图片
     *
     * @param file
     * @return
     */
    public static String encodeImage(File file) {
        FileInputStream fis = null;
        byte[] rs = new byte[0];

        try {
            fis = new FileInputStream(file);
            rs = new byte[fis.available()];
            fis.read(rs);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return Base64.encodeToString(rs, Base64.DEFAULT);
    }

    /**
     * 把一个bitmap对象保存为文件
     *
     * @param fileName
     * @param bitmap
     */
    public static void writeBitmapToFile(String path, String fileName, Bitmap bitmap) {
        if (null == bitmap) {
            return;
        }
        if (TextUtils.isEmpty(fileName)) {
            throw new RuntimeException(" fileName is null");
        }
        FileOutputStream fos = null;
        try {
            File file = new File(createDirToSDCard(path), fileName);
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            CloseUtils.close(fos);
        }
    }

    /**
     * 把一个String对象保存为文件
     *
     * @param fileName
     * @param str
     */
    public static void writeStringToFile(String path, String fileName, String str) {
        if (null == str) {
            return;
        }
        if (TextUtils.isEmpty(fileName)) {
            throw new RuntimeException(" fileName is null");
        }
        FileOutputStream fos = null;
        try {
            File file = new File(createDirToSDCard(path), fileName);
            fos = new FileOutputStream(file);
            fos.write(str.getBytes());
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            CloseUtils.close(fos);
        }
    }

    /**
     * 根据文件路径与名称读取一个字符串值
     *
     * @param path
     * @param fileName
     * @return
     */
    public static String readStringFromFile(String path, String fileName) {
        if (TextUtils.isEmpty(path) || TextUtils.isEmpty(fileName)) {
            throw new IllegalArgumentException(" path or filename is null");
        }

        StringBuilder sb = new StringBuilder();
        BufferedReader br = null;

        try {
            File file = new File(createDirToSDCard(path), fileName);
            Log.d(TAG, file.getAbsolutePath());
            Log.d(TAG, "exists : " + file.exists());
            br = new BufferedReader(new FileReader(file));
            String buf;
            while (null != (buf = br.readLine())) {
                sb.append(buf);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            CloseUtils.close(br);
        }

        return sb.toString();
    }


    /**
     * 把一个对象写到文件里
     *
     * @param path
     * @param fileName
     * @param object
     */
    public static void writeObjectToFile(String path, String fileName, Object object) {
        File file = new File(createDirToSDCard(path), fileName);
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            fos = new FileOutputStream(file);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(object);
            oos.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            CloseUtils.close(fos);
            CloseUtils.close(oos);
        }
    }

    /**
     * 读取一个对象
     *
     * @param path
     * @param fileName
     * @return
     */
    public static Object readObjectFromFile(String path, String fileName) {
        File file = new File(createDirToSDCard(path), fileName);
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {
            fis = new FileInputStream(file);
            ois = new ObjectInputStream(fis);
            Object object = ois.readObject();
            return object;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            CloseUtils.close(fis);
            CloseUtils.close(ois);
        }

        return null;
    }

}
